﻿using System;
using System.ComponentModel;
using System.Windows;
using AMail.Common;
using Elentok.Common.Wpf.Services;

namespace AMail.Start
{
  /// <summary>
  /// Interaction logic for Shell.xaml
  /// </summary>
  public partial class Shell : Window
  {
    #region Private Members
    
    private ExitTrigger exitTrigger = ExitTrigger.None;
    
    #endregion

    public Shell(IShellViewModel viewModel,
      IKeybindingService keybindingService,
      IMenuService menuService)
    {
      InitializeComponent();

      keybindingService.RegisterElement(WindowNames.MainWindow, this);
      fileMenuItems.Collection = menuService.RegisterMenu(MenuNames.FileMenu);
      editMenu.ItemsSource = menuService.RegisterMenu(MenuNames.EditMenu);

      this.DataContext = viewModel;
      viewModel.ExitRequested += new EventHandler(ViewModel_ExitRequested);
    }

    public IShellViewModel ViewModel
    {
      get { return (IShellViewModel)this.DataContext; }
    }

    #region Exit Handlers

    private void ViewModel_ExitRequested(object sender, EventArgs e)
    {
      // if the window triggered the exit, then we're already closing,
      // so no action is necessary
      if (this.exitTrigger == ExitTrigger.Window)
        return;

      this.exitTrigger = ExitTrigger.ViewModel;
      Close();
    }

    protected override void OnClosing(CancelEventArgs e)
    {
      base.OnClosing(e);

      // if it wasn't the viewmodel that triggered the exit,
      // we need to go through the viewmodel's exit command
      if (this.exitTrigger == ExitTrigger.None)
      {
        this.exitTrigger = ExitTrigger.Window;

        ViewModel.ExitCommand.Execute(e);

        // if the exit process was cancelled, reset the exit trigger
        if (e.Cancel)
          this.exitTrigger = ExitTrigger.None;
      }
    }

    #endregion
  }

  /// <summary>
  /// Reasons to exit the application
  /// </summary>
  public enum ExitTrigger
  {
    None,
    ViewModel,
    Window
  }
}
